
import { defineStore } from "pinia";
import { reqCode, reqUserLogin } from "@/api/hospital";
import type { LoginData, UserLoginResponseData } from '@/api/hospital/type'
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from "@/utils/user";
const useUserStore = defineStore('User', {

  state: () => {
    return {
      visiable: false,//用于控制登录组件的dialog显示与隐藏
      userInfo: JSON.parse(GET_TOKEN() as string) || {},
      code: ''
    }
  },
  actions: {

    async getCode(phone: string) {
      let result = await reqCode(phone);
      // console.log(result);

      if (result.code == 200) {
        this.code = result.data
        return 'ok'
      }
      else {
        return Promise.reject(new Error(result.message))
      }
    },

    //用户手机号码登录方法
    async userLogin(loginData: LoginData) {
      //登录请求
      let result: UserLoginResponseData = await reqUserLogin(loginData);
      // console.log(result);

      if (result.code == 200) {
        this.userInfo = result.data;
        //本地存储持久化存储用户信息
        SET_TOKEN(JSON.stringify(this.userInfo));
        //返回一个成功的Promise
        return 'ok';
      } else {
        return Promise.reject(new Error(result.message));
      }
    },

    logout() {
      this.userInfo = { name: '', token: '' };
      REMOVE_TOKEN()
    },
    //查询微信扫码的接口(看本地存储是否存储数据)
    queryState() {
      //开启定时器每隔一段时间问:本地村是都拥有用户信息
      let timer = setInterval(() => {
        //本地存储已有有数据:扫码成功
        // console.log("AAAAAAAAAAAAAAAAAAA");

        if (GET_TOKEN()) {
          //关闭对话框
          this.visiable = false;
          this.userInfo = JSON.parse(GET_TOKEN() as string);
          clearInterval(timer);
        }
      }, 1000);
    }
  },
  getters: {

  }

})

//获取仓库的方法对外暴露
export default useUserStore;